﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Dycox.Workflows
{
    public class InjectionStage : Stage
    {
        public InjectionStage(string name)
            : base(name, StageUsage.Injection)
        {

        }

        private InjectionMode _mode;

        public InjectionMode Mode
        {
            get { return _mode; }
            set
            {
                ThrowIfNotInitializing();
                _mode = value;
            }
        }

        public Stage[] GetDependentStages()
        {
            if (_mode != InjectionMode.Thread)
                throw new WorkflowException("applies_on_thread_injection");

            List<Stage> list = new List<Stage>();

            foreach (var t in Workflow.Transitions)
            {
                if (t.TargetStage == this && t.Type == TransitionTypes.Normal && !list.Contains(t.SourceStage))
                {
                    list.Add(t.SourceStage);
                }
            }

            if (list.Count == 0)
                throw new WorkflowException(SR.GetString("injecting_dependency_not_found"));

            return list.ToArray();
        }

        public Stage GetDependentStage()
        {
            var array = GetDependentStages();
            if (array.Length > 1)
                throw new NotImplementedException("We are not ready to deal with multiple dependent stages for thread injection stage.");
            return array[0];
        }
    }

    public enum InjectionMode
    {
        Process,
        Thread
    }
}
